<?php
/**
 * Created by PhpStorm.
 * User: s.utkin
 * Date: 14.01.2015
 * Time: 12:25
 */

namespace Pinenut\Security\Encryption;


use Pinenut\Security\Encoding\Base64Url;

class LiteEncryptor {
	protected static $xorKeys;

	public static function getXorKeys()
	{
		if (static::$xorKeys == null) {
			static::$xorKeys = \LiteEncryptorConfig::get('xorKeys');
		}

		return static::$xorKeys;
	}

	public static function xorString($inputString, $key)
	{
		$encryptedString = '';
		$inputStringLength = strlen($inputString);
		$keyLength = strlen($key);

		for ($i = 0; $i < $inputStringLength; $i++) {
			$encryptedString .= chr(ord($inputString[$i]) ^ ord($key[$i % $keyLength]));
		}

		return $encryptedString;
	}

	public static function encrypt($inputString)
	{
		$xorKeys = static::getXorKeys();
		$dataCrc32 = crc32($inputString);
		$keyIndex = $dataCrc32 % count($xorKeys);
		$key = $xorKeys[$keyIndex];
		$inputString .= substr(dechex($dataCrc32), -4, 4);

		$encryptedString = static::xorString($inputString, $key);
		$encryptedString = Base64Url::encode($encryptedString);

		return $encryptedString;
	}

	public static function decrypt($encryptedString)
	{
		$encryptedString = Base64Url::decode($encryptedString);
		$encryptedStringLength = strlen($encryptedString);

		$xorKeys = static::getXorKeys();
		$xorKeysLength = count($xorKeys);

		foreach ($xorKeys as $index => $key) {
			$decoded = static::xorString($encryptedString, $key);
			$decodedData = substr($decoded, 0, $encryptedStringLength - 4);
			$decodedDataHash = substr($decoded, $encryptedStringLength - 4, 4);
			$keyIndex = (int)crc32($decodedData) % $xorKeysLength;

			$dataCrc32 = crc32($decodedData);
			$dataHash = substr(dechex($dataCrc32), -4, 4);

			if ($decodedDataHash == $dataHash AND $index == $keyIndex) {
				return $decodedData;
			}
		}

		return null;
	}
} 